package de.tum.in.eist.poll.client.views.widgets.questions;

import java.util.ArrayList;

import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RadioButton;

import de.tum.in.eist.poll.shared.beans.Answer;
import de.tum.in.eist.poll.shared.beans.SingleChoiceAnswer;
import de.tum.in.eist.poll.shared.beans.SingleChoiceQuestion;

/**
 * A question widget for a single choice question
 * @author Sebastian Hofstetter
 * 
 */
public class QuestionSingleChoiceWidget extends QuestionWidget{
	private SingleChoiceQuestion question;
	private VerticalPanel questionPanel = new VerticalPanel();
	private ArrayList<RadioButton> radioButtons = new ArrayList<RadioButton>();
	private Label label;

	public QuestionSingleChoiceWidget(SingleChoiceQuestion question) {
		this.question = question;
		
		label = new Label(this.question.getQuestionText());
		label.addStyleName("question");
		add(label);

		String group = question.toString();	// groups the radioboxes with the question hash
		for (String choice : this.question.getChoices()) {
			RadioButton tmp = new RadioButton(group, choice);
			tmp.setValue(true);	// ensures that one checkbox (the last one added) ist selected
			radioButtons.add(tmp);
			questionPanel.add(tmp);
		}
		add(questionPanel);
	}
	
	/**
	 * returns the index of the selected checkbox
	 * @return the choice, -1 if nothing is chosen
	 */
	public int getChoice() {
		int result = 0;
		for (RadioButton radioButton : radioButtons) {
			if (radioButton.getValue()) {
				return result;
			} else {
				result += 1;
			}
		}
		return -1;
	}

	/* (non-Javadoc)
	 * @see de.tum.in.eist.poll.client.views.widgets.QuestionWidgetInterface#getFeedback(java.lang.String, java.lang.String)
	 */
	@Override
	public Answer getAnswer() {
		return new SingleChoiceAnswer(getChoice());
	}
}
